package com.damai.utils;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.citywithincity.utils.JsonUtil;

public class BeanUtils {

	
	@SuppressWarnings("unchecked")
	public static <T> List<T> readArray(String src, Class<T> clazz) throws Exception {
		List<Map<String, Object>> list = JsonUtil.getMapper().readValue(src, List.class);
		List<T> result = new ArrayList<T>();
		for (Map<String, Object> map : list) {
			result.add(mapToBean(map,clazz ) );
		}
		return result;
	}
	
	
	public static <T> T mapToBean( Map<String, Object> map,Class<T> clazz ) throws Exception{
		 BeanInfo beanInfo = Introspector.getBeanInfo(clazz);  
         PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();  
         T obj = clazz.newInstance();
         for (PropertyDescriptor property : propertyDescriptors) {  
             String key = property.getName();  

             if (map.containsKey(key)) {  
                 Object value = map.get(key);  
                 // 得到property对应的setter方法  
                 Method setter = property.getWriteMethod();  
                 setter.invoke(obj, value);  
             }  

         }  
         return obj;
	}
	
	public static Map<String, Object> beanToMap( Object data ) throws Exception{
		 BeanInfo beanInfo = Introspector.getBeanInfo(data.getClass());  
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();  
        Map<String, Object> map = new HashMap<String, Object>();
        for (PropertyDescriptor property : propertyDescriptors) {  
            String key = property.getName();  
            if(key.equals("class")){
            	continue;
            }
            Method geter = property.getReadMethod();
            Object value = geter.invoke(data);
            map.put(key, value);

        }  
        return map;
	}
	
}
